import { addAddress, getAddress, getAddressDetail } from '@/api/address'

export default {
  namespaced: true,
  state () {
    return {
      addrlist: [{
        name:'',
        tel:''
      }
      ],
      editInfo: {}
    }
  },
  mutations: {
    getAddressList (state, addr) {
      state.addrlist = []
      addr.forEach(item => {
        let addrItem = {
          id: item.address_id,
          name: item.name,
          tel: item.phone,
          address: item.region.province + item.region.city + item.region.region,
          isDefault: true
        }
        state.addrlist.push(addrItem)
      });
    },
    getEdit (state, detail) {
      const res = detail.detail
      state.editInfo = {
        id: res.address_id,
        name: res.name,
        tel: res.phone,
        province: res.region.province,
        city: res.region.city,
        county: res.region.region,
        addressDetail: res.detail,
        areaCode: '17290',
      }
    },
    clearEdit (state) {
      state.editInfo = {}
    }
  },
  actions: {
    // 添加地址
    async addAddress (context, value) {
      const { name, tel, areaCode, prvionce } = value
      const res = await addAddress(name, tel, areaCode, prvionce)
      console.log(res);
    },

    // 获得地址列表
    async getAddress (context) {
      const res = await getAddress()
      context.commit('getAddressList', res.data.list)
    },

    // 获取收货地址详情
    async getAddressDetail (context, id) {
      const res = await getAddressDetail(id)
      context.commit('getEdit', res.data)
    }
  }
}